package com.za.plugin.transfer.form;

/**
 * 在 "join tbl where ..." 这种情况下没有 on ，MySQL 下正常执行，在达梦要改为 "join tbl on true where..."
 */
public class JoinFormTransfer implements FormTransfer {
    @Override
    public boolean isSupport(String sql) {
        return sql.toLowerCase().contains(" join ");
    }

    @Override
    public String transfer(String sql) {
        sql = sql.toLowerCase().replaceAll("\n"," ").replaceAll("\t"," ");
        if (sql.contains(" join ")) {
            int joinIdx = sql.indexOf(" join ");
            StringBuilder sb = new StringBuilder(sql);
            int insertCnt = 0;
            while (joinIdx >= 0) {
                int whereIdx = sql.indexOf(" where ", joinIdx);
                if (whereIdx < 0) {
                    break;
                }
                String substring = " " + sql.substring(joinIdx + 6, whereIdx) + " ";
                if (!substring.contains(" on ") && (substring.trim().split("\\s+").length <= 2)) {
                    sb.insert(whereIdx + 1 + insertCnt * 9, " on true ");
                    insertCnt++;
                }
                joinIdx = sql.indexOf(" join ", joinIdx + 6);
            }
            if (insertCnt > 0) {
                sql = sb.toString();
            }
        }
        return sql;
    }
}
